package cn.tedu.charging.order.timer;

import cn.tedu.charging.common.pojo.po.ChargingBillExceptionPO;
import cn.tedu.charging.common.pojo.po.ChargingBillSuccessPO;
import cn.tedu.charging.order.mapper.BillExceptionMapper;
import cn.tedu.charging.order.mapper.BillSuccessMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xxl.job.core.context.XxlJobContext;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 处理订单正常开始充电后 异常结束判断
 */
@Component
@Slf4j
public class OrderExceptionJob {
    @Autowired
    private BillSuccessMapper billSuccessMapper;
    @Autowired
    private BillExceptionMapper billExceptionMapper;
    //绑定bean模式的jobHandler名字
    @XxlJob("order-status-check")
    public void checkOrderStatus(){
        log.info("订单异常状态检查 开始执行");
        String orderNo = XxlJobContext.getXxlJobContext().getJobParam();
        //1.读取订单完整详情po
        //select * from bill_success where bill_id=#{}
        ChargingBillSuccessPO success=getOrderByBillId(orderNo);
        //2.判断非空时 status
        if (success!=null&&success.getBillStatus()==1){
            //2.1 订单满足异常条件.创建异常订单,结束当前订单 状态改成3 异常结束,通知设备检查修改设备状态
            saveExceptionBill(success);
            //修改订单状态 让订单结束 3
            updateBillStatus(orderNo,3);
            //TODO 告诉用户 结束了 可以支付了,没有充完 sorry
        }else{
            //2.2订单已经结束 检查定时任务完成
            return ;
        }
    }

    private void updateBillStatus(String orderNo, Integer status) {
        //update bill_success set status=? where bill_id=?
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.setSql("bill_status="+status);
        updateWrapper.eq("bill_id",orderNo);
        billSuccessMapper.update(updateWrapper);
    }

    private void saveExceptionBill(ChargingBillSuccessPO success) {
        ChargingBillExceptionPO exceptionPO=new ChargingBillExceptionPO();
        //billId
        exceptionPO.setBillId(success.getBillId());
        //异常原因
        exceptionPO.setCreateTime(new Date());
        billExceptionMapper.insert(exceptionPO);
    }

    private ChargingBillSuccessPO getOrderByBillId(String orderNo) {
        QueryWrapper<ChargingBillSuccessPO> queryWrapper = new QueryWrapper<ChargingBillSuccessPO>();
        queryWrapper.eq("bill_id", orderNo);
        return billSuccessMapper.selectOne(queryWrapper);
    }
}
